//
//  NYAccountViewController.m
//  Nooryes
//
//  Created by baken on 2020/2/26.
//  Copyright © 2020 MyApp. All rights reserved.
//

#import "NYAccountViewController.h"
#import "NYAcccountViewModel.h"
#import "NYRecommendCollectionViewCell.h"
#import "CHTCollectionViewWaterfallLayout.h"
#import "NYArticleListModel.h"
#import "NYTopicListTableViewCell.h"
#import "UIImage+Render.h"
#import "NYSettingViewController.h"
#import "NYLoginViewController.h"
#import "AccountModel.h"
#import "NYTopicArticlesViewController.h"
#import "NYTopicListModel.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "NYAlertView.h"
#import "NYArticleDetailViewController.h"



@interface NYAccountViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UIImageView *avatar;

@property (weak, nonatomic) IBOutlet UILabel *accountDiscription;

@property (weak, nonatomic) IBOutlet UILabel *like;

@property (weak, nonatomic) IBOutlet UILabel *subscribtion;

@property (weak, nonatomic) IBOutlet UILabel *msgNum;

@property (weak, nonatomic) IBOutlet UIView *titleView;

@property (weak, nonatomic) IBOutlet UIView *contentView;

@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;

@property (weak, nonatomic) IBOutlet UIView *redLine;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NYAcccountViewModel *accountVM;

@property (nonatomic, strong) UIButton *selectedBtn;

@property (nonatomic, strong) UILabel *nameLabel;

@property (nonatomic, strong) UILabel *idLabel;

@property (weak, nonatomic) IBOutlet UIView *unLoginView;

@end

@implementation NYAccountViewController

-(NYAcccountViewModel *)accountVM{
    if (!_accountVM) {
        _accountVM = [NYAcccountViewModel new];
    }
    return _accountVM;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (myDelegate.account) {
        self.unLoginView.hidden = YES;
        [self.avatar sd_setImageWithURL:[NSURL URLWithString:myDelegate.account.image] placeholderImage:[UIImage imageNamed:@"sign_logo"]];
        self.like.text = STR_FROM_INT(myDelegate.account.zan);
        self.subscribtion.text =  STR_FROM_INT(myDelegate.account.collect);
        self.accountDiscription.text = myDelegate.account.intro;
        self.nameLabel.text = myDelegate.account.nickname;
        self.idLabel.text = [NSString stringWithFormat:@"ID:%@",myDelegate.account.no];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNameWithOriginal:@"setup"] style:UIBarButtonItemStylePlain target:self action:@selector(onSetting)];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNameWithOriginal:@"share"] style:UIBarButtonItemStylePlain target:self action:@selector(onShare)];
        [self.collectionView.mj_header beginRefreshing];
        [self.tableView.mj_header beginRefreshing];
        
    } else{
        self.unLoginView.hidden = NO;
        self.nameLabel.text = nil;
        self.idLabel.text = nil;
        self.navigationItem.rightBarButtonItem = nil;
        self.navigationItem.leftBarButtonItem = nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.rowHeight = (kScreenWidth-24-6)*0.33 + 35;
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[NYRecommendCollectionViewCell class] forCellWithReuseIdentifier:kNYRecommendCollectionViewCell];
    
    
    
    UIView* titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 40)];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 25)];
    nameLabel.textColor = UIColorFromRGB(0x333333);
    nameLabel.font = [UIFont boldSystemFontOfSize:16];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    self.nameLabel = nameLabel;
    [titleView addSubview:nameLabel];
    UILabel *idLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, 200, 15)];
    idLabel.font = [UIFont systemFontOfSize:12];
    idLabel.textColor = UIColorFromRGB(0x999999);
    idLabel.textAlignment = NSTextAlignmentCenter;
    self.idLabel = idLabel;
    [titleView addSubview:idLabel];
    self.navigationItem.titleView = titleView;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didLogin) name:@"login" object:nil];
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.accountVM.articlePage = 1;
        [self.accountVM getArticleCollectListWithCompletionHandle:^(NSError *error) {
            if (!error) {
                [self.collectionView reloadData];
            }
            [self.collectionView.mj_header endRefreshing];
        }];
    }];
    
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.accountVM.articlePage++;
        [self.accountVM getArticleCollectListWithCompletionHandle:^(NSError *error) {
            if (!error) {
                [self.collectionView reloadData];
            }
            [self.collectionView.mj_footer endRefreshing];
        }];
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.accountVM.topicPage = 1;
        [self.accountVM getTopicCollectListWithCompletionHandle:^(NSError *error) {
            if (!error) {
                [self.tableView reloadData];
            }
            [self.tableView.mj_header endRefreshing];
        }];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.accountVM.topicPage++;
        [self.accountVM getTopicCollectListWithCompletionHandle:^(NSError *error) {
            if (!error) {
                [self.tableView reloadData];
            }
            [self.tableView.mj_footer endRefreshing];
        }];
    }];
    
    [self.accountVM getMessageCountWithCompletionHandle:^(NSError *error) {
        if (!error) {
            if (self.accountVM.msgCount>0) {
                self.msgNum.text = self.accountVM.msgCount;
                self.msgNum.hidden = NO;
            }
        }
    }];
}

-(void)didLogin{
    self.unLoginView.hidden = YES;
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:myDelegate.account.image] placeholderImage:[UIImage imageNamed:@"sign_logo"]];
    self.like.text =  STR_FROM_INT(myDelegate.account.zan);
    self.accountDiscription.text = myDelegate.account.intro;
    self.subscribtion.text =  STR_FROM_INT(myDelegate.account.collect);
    self.nameLabel.text = myDelegate.account.nickname;
    self.idLabel.text = [NSString stringWithFormat:@"ID:%@",myDelegate.account.no];
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNameWithOriginal:@"setup"] style:UIBarButtonItemStylePlain target:self action:@selector(onSetting)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNameWithOriginal:@"share"] style:UIBarButtonItemStylePlain target:self action:@selector(onShare)];
    
    [self.collectionView.mj_header beginRefreshing];
    [self.tableView.mj_header beginRefreshing];
}
- (IBAction)onMessage:(id)sender {
    self.msgNum.hidden = YES;
    [[NSUserDefaults standardUserDefaults] setObject:self.accountVM.msgCount forKey:@"msgCount"];
}

-(void)onSetting{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"NYLoginStoryboard" bundle:nil];
    NYSettingViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"NYSettingViewController"];
    vc.phone = myDelegate.account.phone;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)onShare{
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:myDelegate.account.shareintro
                                     images:@[myDelegate.account.shareimg]
                                        url:[NSURL URLWithString:myDelegate.account.shareurl]
                                      title:myDelegate.account.sharetitle
                                       type:SSDKContentTypeAuto];
    
    [ShareSDK showShareActionSheet:nil
                       customItems:nil
                       shareParams:shareParams
                sheetConfiguration:nil
                    onStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
        switch (state) {
            case SSDKResponseStateSuccess:
            {
                NYAlertView *alert = [NYAlertView sharedAlertView];
                alert.title = @"分享成功";
                [alert showAlert:^{ }];
                break;
            }
            case SSDKResponseStateFail:
            {
                NYAlertView *alert = [NYAlertView sharedAlertView];
                alert.title = @"分享失败";
                [alert showAlert:^{ }];
                break;
            }
            default:
                break;
        }
    }];
}

- (IBAction)onArtical:(id)sender {
    self.selectedBtn.selected = NO;
    UIButton *btn = (UIButton *)sender;
    btn.selected = YES;
    self.selectedBtn = btn;
    self.redLine.center = CGPointMake(self.titleView.frame.size.width * 0.25, self.redLine.center.y);
    
    //    [UIView animateWithDuration:0.2 animations:^{
    //        [self.view layoutIfNeeded];
    //    }];
    self.collectionView.hidden = NO;
    self.tableView.hidden = YES;
}

- (IBAction)onTopic:(id)sender {
    self.selectedBtn.selected = NO;
    UIButton *btn = (UIButton *)sender;
    btn.selected = YES;
    self.selectedBtn = btn;
    self.redLine.center = CGPointMake(self.titleView.frame.size.width * 0.75, self.redLine.center.y);
    
    //    [UIView animateWithDuration:0.2 animations:^{
    //        [self.view layoutIfNeeded];
    //    }];
    self.collectionView.hidden = YES;
    self.tableView.hidden = NO;
    
}

- (IBAction)onSpecial:(id)sender {
    
    
}

- (IBAction)onLogin:(id)sender {
    [self login:sender];
}

- (void)login:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"NYLoginStoryboard" bundle:nil];
    NYLoginViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"NYLoginViewController"];
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
}


#pragma mark - UICollectionView Delegate


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.accountVM.articalArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NYRecommendCollectionViewCell *cell = [NYRecommendCollectionViewCell cellWithCollectionView:collectionView indePath:indexPath];
    ArticleListModel *model = [self.accountVM.articalArray objectAtIndex:indexPath.row];
    cell.model = model;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.image] placeholderImage:[UIImage imageNamed:@"loading"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image) {
            if (!CGSizeEqualToSize(model.imageSize, image.size)) {
                model.imageSize = image.size;
                [collectionView reloadItemsAtIndexPaths:@[indexPath]];
            }
        }
    }];
    
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ArticleListModel *model = [self.accountVM.articalArray objectAtIndex:indexPath.row];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"RecommendStoryboard" bundle:nil];
    NYArticleDetailViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYArticleDetailViewController"];
    detailVC.articleID = model.articleid;
    [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark - CHTCollectionViewDelegateWaterfallLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    ArticleListModel *model = [self.accountVM.articalArray objectAtIndex:indexPath.row];
    if (!CGSizeEqualToSize(model.imageSize, CGSizeZero)) {
        return model.imageSize;
    }
    return CGSizeMake(150, 150);
}


#pragma mark UITableView
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TopicListModel *model = [self.accountVM.topicArray objectAtIndex:indexPath.row];
    NYTopicListTableViewCell *cell = [NYTopicListTableViewCell cellWithTableView:tableView];
    cell.model = model;
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TopicListModel *model = [self.accountVM.topicArray objectAtIndex:indexPath.row];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TopicStoryboard" bundle:nil];
    NYTopicArticlesViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYTopicArticlesViewController"];
    detailVC.topicID = model.talkid;
    [self.navigationController pushViewController:detailVC animated:YES];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.accountVM.topicArray.count;
}


- (BOOL)isLogin{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (delegate.account) {
        return YES;
    } else {
        return NO;
    }
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    UIViewController *destination = segue.destinationViewController;
    if ([destination respondsToSelector:@selector(setPhone:)]) {
        [destination setValue:self.accountVM.account.phone forKey:@"phone"];
        
    }
    
}

@end
